package edu.cuit.zhuyimeng.framework.common.handler;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.SaTokenException;
import edu.cuit.zhuyimeng.framework.common.exception.QueryException;
import edu.cuit.zhuyimeng.framework.common.exception.ServerException;
import edu.cuit.zhuyimeng.framework.common.exception.UpdateException;
import edu.cuit.zhuyimeng.framework.common.result.CommonResult;
import edu.cuit.zhuyimeng.framework.common.result.HttpStatusCodeConstants;
import edu.cuit.zhuyimeng.framework.common.util.ServletUtils;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler
    public void handleException(Exception e, HttpServletResponse response) {

        if (e instanceof MethodArgumentNotValidException exception) {
            ServletUtils.writeCodeJSON(response, CommonResult.error(HttpStatusCodeConstants.BAD_REQUEST,exception.getBindingResult().getAllErrors().get(0).getDefaultMessage()));
        } else if (e instanceof NotLoginException) {
            ServletUtils.writeCodeJSON(response, CommonResult.error(HttpStatusCodeConstants.UNAUTHORIZED,"请进行登录再操作"));
        } else if (e instanceof QueryException || e instanceof UpdateException) {
            ServletUtils.writeCodeJSON(response, CommonResult.error(HttpStatusCodeConstants.BAD_REQUEST,e.getMessage()));
        } else if (e instanceof ServerException) {
            ServletUtils.writeCodeJSON(response, CommonResult.error(HttpStatusCodeConstants.INTERNAL_SERVER_ERROR,e.getMessage()));
            log.error("发生错误: " + e.getMessage());
        } else if (e instanceof HttpRequestMethodNotSupportedException) {
            ServletUtils.writeCodeJSON(response, CommonResult.error(HttpStatusCodeConstants.BAD_REQUEST,e.getMessage()));
        } else if (e instanceof SaTokenException) {
            ServletUtils.writeCodeJSON(response, CommonResult.error(HttpStatusCodeConstants.FORBIDDEN,e.getMessage()));
        } else  {
            e.printStackTrace();
            ServletUtils.writeCodeJSON(response, CommonResult.error(e.getMessage()));
        }

    }

}
